<template>
	<section>
		<!--Alert提示框-->
        <el-alert type="warning" class="alert-style" v-show="hasAlert" @close="fnAlertClose">{{alertMsg}}</el-alert>
		
		<!--添加企业工具条-->
		<el-col :span="24" class="add-toolbar" style="padding-bottom:0px;height: 56px;">
			<el-form :inline="true">
				<el-form-item>
					<el-select v-model="selectManuf" clearable filterable placeholder="工艺名称">
						<el-option-group v-for="group in manufs" :key="group.Code" :label="group.Value">
							<el-option v-for="item in group.Items" :key="item.Code" :label="item.Value" :value="item.Code">
							</el-option>
						</el-option-group>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-cascader placeholder="按省市区过滤" change-on-select clearable expand-trigger="click" :props="props" :options="provincialCity" v-model="selectedCity"></el-cascader>
				</el-form-item>
				<el-form-item>
					<el-select v-model="selectCert" clearable placeholder="按资质证书过滤">
						<el-option v-for="item in certs" :key="item.Code" :label="item.Value" :value="item.Code"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="fnSelectCompany">查询</el-button>
				</el-form-item>
				<el-form-item v-show="hasCheckAuth">
					<el-button type="warning" @click="fnAddCompany">添加企业</el-button>
				</el-form-item>
			</el-form>
		</el-col>
		
		<el-table :data="companys" border style="width: 100%" v-loading="companysLoading" element-loading-text="拼命加载中">
			<el-table-column fixed prop="companyName" label="公司名称" width="230">
			</el-table-column>
			<el-table-column prop="coreBiz" label="核心业务" width="400">
			</el-table-column>
			<el-table-column prop="certs" label="资质证书" width="250" :formatter="fnFormatCert">
			</el-table-column>
			<el-table-column prop="province" label="所在城市" width="260" :formatter="fnFormatProvCity">
			</el-table-column>
			<el-table-column v-if="hasCheckAuth" fixed="right" label="操作" width="145">
				<template scope="scope">
					<el-tooltip class="item" effect="dark" content="编辑操作" placement="bottom">
				      	<el-button size="mini" icon="custom-edit" @click="fnEdit(scope.row.companyid)"></el-button>
				    </el-tooltip>
				    <el-tooltip class="item" effect="dark" content="同步数据" placement="bottom">
				      	<el-button type="info" size="mini" icon="custom-refresh" @click="fnSynchro(scope.row.companyid)"></el-button>
				    </el-tooltip>
				    <el-tooltip class="item" effect="dark" content="删除操作" placement="bottom">
				      	<el-button type="danger" size="mini" icon="custom-delete"  @click="fnDelCompany(scope.row.companyid)"></el-button>
				    </el-tooltip>
				</template>
			</el-table-column>
		</el-table>
		
		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button @click="fnBack">返回</el-button>
			<el-pagination layout="total, prev, pager, next" @current-change="fnPaginationChange" :page-size="size" :total="total" style="float:right;">
			</el-pagination>
		</el-col>
		
		<!--添加企业-->
		<el-dialog title="添加公司" v-model="addFormVisible" :close-on-click-modal="false">
			<el-form :inline="true" :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="公司名称" prop="CompanyName">
					<el-autocomplete v-model="addForm.CompanyName" :fetch-suggestions="querySearchAsync" placeholder="请输入公司名称" @select="fnCompanySel"></el-autocomplete>
				</el-form-item>
				<el-form-item label="联系人" prop="ContactPerson">
					<el-input v-model="addForm.ContactPerson" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="职务" prop="Title">
					<el-input v-model="addForm.Title" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="联系方式" prop="Mobile">
					<el-input v-model="addForm.Mobile" auto-complete="off"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="fnSubmitAudit">提交申请</el-button>
			</div>
		</el-dialog>
		
		
	</section>
</template>

<script>
	import Svc from '../../service/index.js'
	export default {
		data() {
			return {
				alertMsg:'',
				hasAlert:false,
				companysLoading : false,
				//工艺分类
				manufs : this.manufactures = JSON.parse(sessionStorage.getItem('manufactures')),
				//当前选择的工业分类
				selectManuf : '',
				//省市区数据
				provincialCity:[],
				//配置省市区数据
		        props: {
		          	value: 'Name',
		          	label: 'Name',
		          	children: 'Cities'
		        },
		        //选择的省市区
		        selectedCity:'',
		        //资质证书列表
		        certs : [],
		        //当前选择的资质证书
		        selectCert : '',
		        total: 0,
				skip: 0,
				size: 20,
		        //公司列表
		        companys : [],
		        addFormVisible: false,//添加公司界面是否显示
		        addFormRules: {
					CompanyName: [
						{ required: true, message: '请输入公司名称', trigger: 'blur' }
					],
					ContactPerson: [
						{ required: true, message: '请输入联系人名称', trigger: 'blur' }
					],
					Mobile: [
						{ required: true, message: '请输入联系电话', trigger: 'blur' }
					],
					Title: [
						{ required: true, message: '请输入联系人职务', trigger: 'blur' }
					]
				},
				//添加公司数据
				addForm: {
					CompanyID:'',
					CompanyName:'',
					Code:'',
					ContactPerson: '',
					Mobile:'',
					Title: ''
				},
				//判断当前用户是否有权维护工艺下的公司
				hasCheckAuth : false
			}
		},
		methods: {
            //显示message提示框
            openMessage : function(msg,type){
    	        this.$message({
		          	showClose: true,
		          	message: msg,
		          	type: type
		        });
            },
			//格式展示省市区的内容
            fnFormatProvCity: function (row, column) {
            	var provCity = row.province + " " + row.city + " " + row.district;
            	return provCity
			},
			//格式展示证书的内容
			fnFormatCert: function (row, column) {
				var data = row.certs || []
				if (data.length == 0) { return '----' }
				
				var certs = ""
				for (var i=0;i<data.length;i++) {
					certs += data[i] + " "
				}
            	return certs
			},
			//获取省市区列表
			fnGetProvincialCity : function() {
				var that = this
				var provCity = sessionStorage.getItem('provincialCity');
				if (provCity) {
					that.provincialCity = JSON.parse(provCity)
				} else {
					//获取省市区列表
		            Svc.fnGetData('/api/common/cities',{},function(res){
		            	if (res.body.ErrCode == 0){
		            		//将Districts替换为Cities
		            		var data = res.body.Data || []
		            		for (var i = 0; i < data.length; i++) {
		            			var temp = data[i]
		            			if (temp.Cities.length > 0) {
		            				for (var j=0;j<temp.Cities.length;j++) {
			            				var item = temp.Cities[j]
			            				item.Cities = item.Districts
		            					delete item.Districts
			            			}
		            			}
		            		}
		            		//保存省市区列表
		            		that.provincialCity = data
		            		sessionStorage.setItem('provincialCity', JSON.stringify(data));
		            	} else {
		            		that.alertMsg = "省市区列表获取失败！"
		            		that.hasAlert = true
		            	}
		            },function(res){
		            	that.alertMsg = "网络错误，请重新！"
		            	that.hasAlert = true
		            }) 
				}
			},
			//获取资质证书
			fnGetCerts : function() {
				var that = this
				//获取资质证书
	            Svc.fnGetData('/api/common/datadict/certificate',{},function(res){
	            	if (res.body.ErrCode == 0){
	            		that.certs = res.body.Data
	            	} else {
	            		that.alertMsg = "资质证书列表获取失败！"
	            		that.hasAlert = true
	            	}
	            },function(res){
	            	that.alertMsg = "网络错误，请重新！"
	            	that.hasAlert = true
	            }) 
			},
			//获取公司列表
			fnGetCompanys : function(){
				var that = this
				that.companysLoading = true
				//格式化省市区
				var crt = { province : '', city :　'', county : '' }
				if (that.selectedCity.length == 1) {
					crt.province = that.selectedCity[0]
				} else if (that.selectedCity.length == 2) {
					crt.province = that.selectedCity[0]
					crt.city = that.selectedCity[1]
				} else if (that.selectedCity.length == 3) {
					crt.province = that.selectedCity[0]
					crt.city = that.selectedCity[1]
					crt.county = that.selectedCity[2]
				} 
				
				var params = {
					Skip: that.skip*that.size,
					Size: that.size,
					Code : that.selectManuf,
	    			Province : crt.province,
	    			City : crt.city,
	    			District : crt.county,
	    			Cert : that.selectCert
				}
	            Svc.fnPostData('/api/manuf/searchcompany',params,function(res){
	            	if (res.body.ErrCode == 0){
	            		that.companys = res.body.Data.List
	            		that.total = res.body.Data.Total
	            		that.companysLoading = false
	            	} else {
	            		that.alertMsg = "公司列表获取失败！"
	            		that.hasAlert = true
	            	}
	            },function(res){
	            	that.alertMsg = "网络错误，请重新！"
	            	that.hasAlert = true
	            }) 
			},
			//按条件查找（当前工艺+过滤条件）
			fnSelectCompany : function(){
				//判断用户是否有权限维护工艺下的公司
				this.fnCheckAuth()
				this.fnGetCompanys()
			},
			//分页
			fnPaginationChange : function(val) {
				this.skip = val-1;
				this.fnGetCompanys();
			},
            //返回
            fnBack : function(){
            	this.$router.go(-1)
//            	this.$router.push({ path: '/manufacture' });
            },
            //编辑公司
            fnEdit : function(id){
            	this.$router.push({ path: '/companydetail', query: {companyID: id}});
            },
            //删除公司
            fnDelCompany : function(id){
		   		var that = this
		   		var params = {
   			        Code:that.selectManuf,
        			CompanyID:id
		   		}
				that.$confirm('确认要删除该公司吗?', '提示', {
					type: 'warning'
				}).then(function(){
					Svc.fnPostData('/api/manuf/delcompany',params,function(res){
						if (res.body.ErrCode == 0) {
							that.openMessage('公司删除成功！',"success")
							setTimeout(function () {
			         			//刷新当前组件
	            				that.$router.go(0)
				          	},1500);
						} else {
							that.openMessage(res.body.ErrMsg,"error")
						}
					})
				});
            },
            //同步数据
            fnSynchro : function(id){
		   		var that = this
				that.$confirm('确认要同步该公司的数据吗?', '提示', {
					type: 'warning'
				}).then(function(){
					Svc.fnPostData('/api/manuf/reindex',{ID:id},function(res){
						if (res.body.ErrCode == 0) {
							that.openMessage('公司数据同步成功！',"success")
				         	setTimeout(function () {
			         			//刷新当前组件
	            				that.$router.go(0)
				          	},1500);
						} else {
							that.openMessage(res.body.ErrMsg,"error")
						}
					})
				});
            },
            //展示添加企业页面
            fnAddCompany : function(){
            	var that = this
            	that.addFormVisible = true
            },
            //模糊搜索公司名
	        querySearchAsync : function(queryString, cb) {
	        	var that = this
	        	var results = []
	        	if (queryString) {
			    	Svc.fnGetData('/api/corp/search/' + queryString,{},function(res){
						if (res.body.ErrCode == 0) {
							for (var i=0;i<res.body.Data.length;i++) {
								var item = res.body.Data[i]
								results.push({
									"value":item.companyName,
									"id" :item.companyId
								})
							}
						} else {
							that.openMessage(res.body.ErrMsg,"error")
						}
					})
	        	} else {
	        		results = []
	        	}
		        cb(results);
		    },
		    //选择搜索到公司名
		    fnCompanySel : function(item){
		    	var that = this
		    	that.addForm.CompanyID = item.id
		    	that.addForm.CompanyName = item.value
		    },
		    //提交申请
		    fnSubmitAudit : function(){
		    	var that = this
		    	that.addForm.Code = that.selectManuf
		    	that.$refs.addForm.validate((valid) => {
		          	if (valid) {
		          		Svc.fnPostData('/api/manuf/addcompany',that.addForm,function(res){
							if (res.body.ErrCode == 0) {
								that.addFormVisible = false
								that.openMessage('添加公司申请提交成功！',"success")
							} else {
								that.openMessage(res.body.ErrMsg,"error")
							}
						})
		          	}
		        });
		    },
		    //判断用户是否有权限维护工艺下的公司
		    fnCheckAuth : function(){
		    	var that = this
				Svc.fnGetData('/api/manuf/checkauth/'+that.selectManuf,{},function(res){
					that.hasCheckAuth = res.body.Data
				})
		    }
		},
		mounted() {
			var that = this
			//设置初始值
			that.selectManuf = that.$route.query.code;
			//获取省市区列表
			that.fnGetProvincialCity()
			//获取资质证书
			that.fnGetCerts()
			//获取公司列表
			that.fnGetCompanys()
			//判断用户是否有权限维护工艺下的公司
			that.fnCheckAuth()
		}
	}

</script>

<style scoped>
	.add-toolbar {
	    background: #f2f2f2;
	    padding: 10px 10px 0 10px;
	    margin: 10px 0;
	}
	
	.toolbar {
	    background: #f2f2f2;
	    padding: 10px;
	    margin: 10px 0;
	}
	
	/*.valid-toolbar {
	    background: #f2f2f2;
	    padding: 0 10px;
	    margin: 0 0 10px 0;
	}*/
</style>